package com.jit.BluetoothKey.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.jit.BluetoothKey.R;
import com.jit.BluetoothKey.activity.base.BaseActivity;
import com.jit.BluetoothKey.adapt.BluetoothConnectionAdapt;
import com.jit.BluetoothKey.entity.BleMessageDTO;
import com.jit.BluetoothKey.utils.SharedPreferencesUtil;
import com.jit.BluetoothKey.utils.UserFiled;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 蓝牙连接列表显示
 */

public class BluetoothConnectionActivity extends BaseActivity implements View.OnClickListener {


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    BleMessageDTO bleMessageDTO = (BleMessageDTO) msg.obj;
                    SharedPreferencesUtil.setString(BluetoothConnectionActivity.this,UserFiled.BINGDING_BLUETOOTH,bleMessageDTO.getMac());
                    SharedPreferencesUtil.setString(BluetoothConnectionActivity.this,UserFiled.BINGDING_BLUETOOTH_NAME,bleMessageDTO.getName());
                    bindBluetoothVisible();

                    // TODO: 2018/2/27   绑定蓝牙发送信息到主界面 扫描连接蓝牙
                    EventBus.getDefault().post(UserFiled.BLE_CHANGE);
                    break;
            }
            return true;
        }
    });
    private ListView listView;
    private BluetoothConnectionAdapt adapt;
    private ImageView freshIv;
    private Animation rotateAnimation;
    private List<BleDevice> bluetoothDevice = new ArrayList<>();
    private boolean isScaning = false;    // 标识是否正在扫描
    private LinearLayout connectionLl;
    private TextView headBingdingBluetoothName;  // 绑定头部名称

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_connection);
        bluetoothScan(); // 进入页面开始扫描附近蓝牙设备
    }



    private void bluetoothScan() {
        Log.i("tag", "bluetoothScan: ");
        bluetoothDevice.clear();  //扫描前清空蓝牙设备列表
        /**
         *  扫描的监听回调
         */
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                if (success) {
                    freshIv.startAnimation(rotateAnimation);
                    isScaning = true;
                }
            }

            @Override
            public void onScanning(BleDevice result) {
                Log.i("tag", "onScanning: ===============>");
                if (result != null) {
                    bluetoothDevice.add(result);
                    adapt.notifyDataSetChanged();
                }
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                isScaning = false;
                freshIv.clearAnimation();

            }
        });
    }

    /**
     *   判断当前是否绑定蓝牙
     */
    private void bindBluetoothVisible(){
        if (SharedPreferencesUtil.getString(this, UserFiled.BINGDING_BLUETOOTH).equals("")){
            connectionLl.setVisibility(View.GONE);
        }else {
            connectionLl.setVisibility(View.VISIBLE);
            headBingdingBluetoothName.setText(SharedPreferencesUtil.getString(this, UserFiled.BINGDING_BLUETOOTH_NAME).equals("")?
                    SharedPreferencesUtil.getString(this, UserFiled.BINGDING_BLUETOOTH):SharedPreferencesUtil.getString(this, UserFiled.BINGDING_BLUETOOTH_NAME));
        }
    }

    @Override
    protected void initView() {
        super.initView();
        listView = (ListView) findViewById(R.id.bluetooth_connection_lv);
        View headView = View.inflate(this, R.layout.item_head_connection_head, null);
        connectionLl = headView.findViewById(R.id.head_connection_ll);
        headBingdingBluetoothName = headView.findViewById(R.id.head_connection_name_tv);
        bindBluetoothVisible();
        listView.addHeaderView(headView);
        freshIv = (ImageView) findViewById(R.id.bluetootn_connection_fresh_iv);
        rotateAnimation = AnimationUtils.loadAnimation(this, R.anim.bluetooth_rotate_anim);
    }



    @Override
    protected void initData() {
        super.initData();

    }

    @Override
    protected void initAdapt() {
        super.initAdapt();
        adapt = new BluetoothConnectionAdapt(this, bluetoothDevice,handler);
        listView.setAdapter(adapt);
    }

    @Override
    protected void initListner() {
        super.initListner();
        freshIv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bluetootn_connection_fresh_iv:
                if (isScaning) {
                    BleManager.getInstance().cancelScan();
                } else {
                    bluetoothScan();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance().cancelScan();
    }
}
